function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }

  let _lastTime = null

  // 返回新的函数
  return function () {
    let _nowTime = + new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments)   //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}

function debounce(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 300
  }
  let timeout = null
  // 返回新的函数
  return function () {
	  if(timeout !== null)  clearTimeout(timeout);        
	  timeout = setTimeout(()=>{
		  fn.apply(this, arguments)
	  },gapTime); 
  }
}

function dateFormat (value) {
  if (value) {
    let dateFormat = new Date()
    dateFormat.setTime(value)
    return dateFormat.getFullYear() + '-' + ((dateFormat.getMonth() + 1) < 10 ? '0' + (dateFormat.getMonth() + 1) : (dateFormat.getMonth() + 1)) + '-' + (dateFormat.getDate() < 10 ? '0' + dateFormat.getDate() : dateFormat.getDate())
  } else {
    return ''
  }
}

// 版本对比
function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

function generateRandomString(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  
  return result;
}

module.exports = {
	throttle:throttle,
	debounce:debounce,
  dateFormat: dateFormat,
  compareVersion,
  generateRandomString
}